package org.csu.myPetStore.web.servlet;

import org.csu.myPetStore.domain.Account;
import org.csu.myPetStore.domain.Cart;
import org.csu.myPetStore.service.LogcatService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;

public class ViewCartServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String LOGIN = "/WEB-INF/jsp/account/SignonForm.jsp";


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        LogcatService logcatService = new LogcatService();

        Account account = (Account) session.getAttribute("account");

        if(account == null){
            req.getRequestDispatcher(LOGIN).forward(req,resp);
        } else{
            java.util.Date date = new java.util.Date();
            Date datesql = new Date(date.getTime());
            logcatService.InsertLogCat(account.getUsername(),account.getUsername() + " View Cart  at " + datesql.toString());

            if(cart == null){
                cart = new Cart();
                session.setAttribute("cart",cart);
            }
            req.getRequestDispatcher(VIEW_CART).forward(req,resp);
        }
    }

}
